package org.dfzt.modules.system.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dfzt.common.system.util.JwtUtil;
import org.dfzt.common.util.SpringContextUtils;
import org.dfzt.modules.system.entity.SysUser;
import org.dfzt.modules.system.service.ISysUserService;
import org.dfzt.modules.system.service.impl.SysUserServiceImpl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 密码任务类
 * @author: cuiyf
 * @Date: 2020/6/24 10:12
 * @Version: 1.0
 */
public class PasswordJob implements SimpleJob {
    private static final Log log = LogFactory.getLog(PasswordJob.class);

    private ISysUserService sysUserService;
    @Override
    public void execute(ShardingContext shardingContext) {
        if (sysUserService == null){
            sysUserService = SpringContextUtils.getBean(SysUserServiceImpl.class);
        }
        Calendar pwd = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        Date date = new Date();
        now.setTime(date);

        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getStatus,1));
        list.forEach(i -> {
            if (i.getPasswordUpdateTime() == null){
                pwd.setTime(i.getCreateTime());
            } else {
                pwd.setTime(i.getPasswordUpdateTime());
            }
            pwd.add(Calendar.MONTH, JwtUtil.PASSWORD_VALIDITY);
            if (pwd.before(now)){
                try {
                    sysUserService.update(new LambdaUpdateWrapper<SysUser>()
                            .set(SysUser::getNeedUpdatePw,"1")
                            .eq(SysUser::getId, i.getId()));
                } catch (Exception e) {
                    log.error("更新状态失败：", e);
                }
            }
        });
    }
}
